package com.wjs.gulimall.seckill.service.imp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.wjs.gulimall.seckill.feign.CouponFeignService;
import com.wjs.gulimall.seckill.feign.ProductFeignService;
import com.wjs.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.wjs.gulimall.seckill.service.SecKillService;
import com.wjs.gulimall.seckill.to.SecKillSkuRedisTo;
import com.wjs.gulimall.seckill.vo.SecKillSessionsWithSkus;
import com.wjs.gulimall.seckill.vo.SeckillSkuVo;
import com.wjs.gulimall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SecKillServiceImp implements SecKillService {
    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions";

    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    @Override
    public void uploadSeckillSkuLatest3Days() {
        R r = couponFeignService.getLates3DaySession();
        if (r.getCode() == 0) {
            List<SecKillSessionsWithSkus> data = (List<SecKillSessionsWithSkus>) r.getData(new TypeReference<List<SecKillSessionsWithSkus>>() {
            });
            //拿到数据后缓存到redis
            //1 缓存活动数据
            if(data!=null&&data.size()>0){
                saveSessionInfos(data);
                saveSessionSkuInfos(data);
            }
        }
    }

    @Override
    public List<SecKillSkuRedisTo> getCurrentSeckillSkus() {
        //获取当前时间
        long time = new Date().getTime();
        Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        for (String key : keys) {
            String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
            String[] s = replace.split("_");
            long startTime = Long.parseLong(s[0]);
            long endTime = Long.parseLong(s[1]);
            if (time >= startTime && time <= endTime) {
                //获取这个秒杀相关的商品信息
                BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                if (range != null) {
                    List<String> list = ops.multiGet(range);
                    List<SecKillSkuRedisTo> collect = list.stream().map(item -> {
                        SecKillSkuRedisTo redisTo = JSON.parseObject(item, SecKillSkuRedisTo.class);
                        return redisTo;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }
        return null;
    }

    @Override
    public SecKillSkuRedisTo getSkuSecKillInfo(Long skuId) {
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = ops.keys();
        if (keys != null && keys.size() > 0) {
            for (String key : keys) {
                String[] s = key.split("_");
                if (s[1].equals(skuId.toString())) {
                    String json = ops.get(key);
                    SecKillSkuRedisTo redisTo = JSON.parseObject(json, SecKillSkuRedisTo.class);
                    long now = new Date().getTime();
                    Long startTime = redisTo.getStartTime();
                    Long endTime = redisTo.getEndTime();
                    if (!(now >= startTime && now <= endTime)) {
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        long begin = System.currentTimeMillis();
        MemberRespVo respVo = LoginUserInterceptor.loginUser.get();
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = ops.get(killId);
        if (StringUtils.isEmpty(json)) {
            return null;
        } else {
            //成功的逻辑
            //1 判断是否过期
            SecKillSkuRedisTo redisTo = JSON.parseObject(json, SecKillSkuRedisTo.class);
            long time = new Date().getTime();
            Long start = redisTo.getStartTime();
            Long end = redisTo.getEndTime();
            if (time >= start && time <= end) {
                //成功的逻辑
                //判断随机码是否准确
                String randomCode = redisTo.getRandomCode();
                String skuid = redisTo.getPromotionSessionId() + "_" + redisTo.getSkuId();
                if (randomCode.equals(key) && killId.equals(skuid)) {
                    //成功
                    //验证商品的购买数量是否合理
                    Integer limit = redisTo.getSeckillLimit();
                    if (num <= limit) {
                        //购买后进行幂等性操作，进行占位置
                        String redisKey = respVo.getId() + "_" + skuid;
                        //设置自动过期时间
                        long ttl = end - time;
                        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (ifAbsent) {
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            try {
                                boolean acquire = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                                if(acquire){
                                    String timeId= IdWorker.getTimeId();
                                    SeckillOrderTo orderTo = new SeckillOrderTo();
                                    orderTo.setOrderSn(timeId);
                                    orderTo.setMemberId(respVo.getId());
                                    orderTo.setNum(num);
                                    orderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                                    orderTo.setSkuId(redisTo.getSkuId());
                                    orderTo.setSeckillPrice(redisTo.getSeckillPrice());
                                    long ends = System.currentTimeMillis();
                                    log.info("秒杀业务耗时{}ms",ends-begin);
                                    //秒杀成功后往rabbitmq发消息
                                    rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", orderTo);
                                    return timeId;
                                }else {
                                    return null;
                                }
                            } catch (InterruptedException e) {
                                return null;
                            }
                        } else {
                            return null;
                        }
                    } else {
                        return null;
                    }
                } else {
                   return null;
                }
            } else {
                return null;
            }
        }
    }

    /**
     * redis缓存活动信息
     *
     * @param sessions
     */
    private void saveSessionInfos(List<SecKillSessionsWithSkus> sessions) {
        sessions.stream().forEach(s -> {
            Long startTime = s.getStartTime().getTime();
            Long endTime = s.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
            Boolean hasKey = redisTemplate.hasKey(key);
            //保证幂等性
            if (!hasKey) {
                List<String> list = s.getRelationSkus().stream().map(item -> {
                    return item.getPromotionSessionId() + "_" + item.getSkuId().toString();
                }).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key, list);
            }
        });
    }

    /**
     * redis缓存商品信息
     *
     * @param sessions
     */
    private void saveSessionSkuInfos(List<SecKillSessionsWithSkus> sessions) {
        sessions.stream().forEach(s -> {
            BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            s.getRelationSkus().stream().forEach(k -> {
                String token = UUID.randomUUID().toString().replace("-", "");
                if (!hashOps.hasKey(k.getPromotionSessionId().toString() + "_" + k.getSkuId().toString())) {
                    SecKillSkuRedisTo redisTo = new SecKillSkuRedisTo();
                    BeanUtils.copyProperties(k, redisTo);

                    R r = productFeignService.info(k.getSkuId());
                    if (r.getCode() == 0) {
                        SkuInfoVo skuInfo = (SkuInfoVo) r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfoVo(skuInfo);
                    }

                    redisTo.setStartTime(s.getStartTime().getTime());
                    redisTo.setEndTime(s.getEndTime().getTime());
                    redisTo.setRandomCode(token);
                    String jsonString = JSON.toJSONString(redisTo);
                    hashOps.put(k.getPromotionSessionId().toString() + "_" + k.getSkuId().toString(), jsonString);
                    //引入分布式的信号量
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    //商品可以秒杀的数量
                    semaphore.trySetPermits(k.getSeckillCount());
                }
            });
        });
    }
}
